<?php

namespace App;

use App\Model\Article;
use App\Model\Favorite;
use App\Model\Topic;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\DatabaseNotification;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable{
        notify as protected notify_cx;
    }
    //此处重写 消息通知排序的方法， 使未读的消息排序在前。
    public function notifications()
    {
        return $this->morphMany(DatabaseNotification::class, 'notifiable')->orderBy('read_at', 'asc');
    }
    //此处重写 自己评论自己的消息不发送通知

    public function notify($instance)
    {
        //如果当前登陆用户 不等于文章 id 就发送通知
        if(auth()->id()!= $this->id){
            $this->notify_cx($instance);
        }

    }

    protected $guarded = ['password_confirmation'];
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    //key为 Icon字段的值
    public function getIconAttribute($key)
    {
        return $key?:asset('images/default.jpeg');
    }

    //获取文章表数据 一对多模型关联
    public  function article(){
        return $this->hasMany(Article::class);
    }
    //获取当前用户的粉丝
    public function fans(){

       return $this->belongsToMany(User::class,'fans','user_id','fans_id');
    }

    //获取关注了谁
    public function follower(){

       return $this->belongsToMany(User::class,'fans','fans_id','user_id');
    }

    //是否关注
    public function isfollower(User $user){

        return $this->follower->contains ( $user );
    }

    //收藏的文章
    public function favorite(){
        return $this->hasMany(Favorite::class);
    }
    //关联话题模型

    public function topic(){

        return $this->hasMany(Topic::class);
    }
}
